//
//  LGTemporaryStopController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/8/21.
//  临时停诊

#import "LGTemporaryStopController.h"
#import "LGCloseAppointView.h"
#import "FSCalendar.h"
#import "LGSchedulStopView.h"
@interface LGTemporaryStopController ()<FSCalendarDelegate,FSCalendarDataSource,UITableViewDelegate,UITableViewDataSource>
/**   */
@property (nonatomic , strong)UIButton *leftButton;
/**   */
@property (nonatomic , strong)UIButton *rightButton;
/**   */
@property (nonatomic , strong)UILabel *mounthLabel;
/**   */
@property (nonatomic , strong)FSCalendar *calendar;
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)UIButton *stopButton;
/**   */
@property (nonatomic , strong)NSDateFormatter *formatter;
/**   */
@property (nonatomic , strong)NSDateFormatter *monthFormatter;
/**   */
@property (nonatomic , strong)NSArray *amArray;
/**   */
@property (nonatomic , strong)NSArray *pmArray;
/**   */
@property (nonatomic , copy)NSString *currentDate;
/**   */
@property (nonatomic , copy)NSString *stopids;

@end

@implementation LGTemporaryStopController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.gradientLayer.hidden = YES;
    self.view.backgroundColor = [UIColor colorWithString:@"#F9F9F9"];
    self.currentDate = [self.formatter stringFromDate:[NSDate date]];
    [self.view addSubview:self.leftButton];
    [self.view addSubview:self.mounthLabel];
    [self.view addSubview:self.rightButton];
    [self.view addSubview:self.calendar];
    [self.view addSubview:self.tableView];
    [self.tableView addSubview:self.stopButton];
    [self.calendar selectDate:[NSDate date]];
    [self requestData];
    [self.tableView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureAction)]];
}

-(void)requestData{
    [RequestUtil withPOST:@"/doctor/visit.Visit_close/schedule" parameters:@{@"date":self.currentDate} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            self.amArray = returnData[@"am"];
            self.pmArray = returnData[@"pm"];
            [self.tableView reloadData];
        }
    } error:^(NSError *error) {
        
    }];
}


//上个月 、下个月
-(void)monthBtnAction:(UIButton *)sender{
    NSDate *currentPatent = self.calendar.currentPage;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:(NSCalendarUnitMonth | NSCalendarUnitYear) fromDate:currentPatent];
    
    if (sender == self.leftButton) {
        [components setMonth:components.month-1];
    }else{
        [components setMonth:components.month+1];
    }
    currentPatent = [calendar dateFromComponents:components];
    [self.calendar setCurrentPage:currentPatent animated:YES];
    self.mounthLabel.text = [self.monthFormatter stringFromDate:currentPatent];
    
    NSInteger year = [[self.mounthLabel.text substringToIndex:4] integerValue];
    NSInteger month = [[self.mounthLabel.text substringWithRange:NSMakeRange(5, 2)] integerValue];
    
  
    
//    if(year<self.currentYear || (year == self.currentYear && month<self.currentMonth)){
//        self.rightBtn.userInteractionEnabled = YES;
//        self.rightBtn.selected = NO;
//    }else{
//        self.rightBtn.userInteractionEnabled = NO;
//        self.rightBtn.selected = YES;
//    }
}


//点击选中日期
- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{
    NSTimeInterval time = [date timeIntervalSinceDate:[NSDate date]];
    int days = ((int)time)/(3600*24);
    if(days<=13){
        self.currentDate = [self.formatter stringFromDate:date];
        self.mounthLabel.text = [self.monthFormatter stringFromDate:date];
        [self requestData];
    }else{
        [TooltipView showMessage:@"无法设置2周以外的临时停诊" offset:0];
        [self.calendar selectDate:[self.formatter dateFromString:self.currentDate]];
    }
    self.stopButton.hidden = YES;
    
}

//滑动、切换月份后默认选中日期
- (void)calendarCurrentPageDidChange:(FSCalendar *)calendar{
    self.mounthLabel.text = [self.monthFormatter stringFromDate:calendar.currentPage];
//    if (calendar.currentPage == calendar.today) {
//        calendar.appearance.titleTodayColor = [UIColor colorWithString:@"#FFFFFF"];
//    }else{
//        calendar.appearance.titleTodayColor = [UIColor colorWithString:@"#2B2A37"];
//    }
//    [calendar selectDate:calendar.currentPage];
}

//停诊、接诊
-(void)stopButtonAction:(UIButton *)sender{
    self.stopButton.hidden = YES;
    if(sender.selected == YES){
        //接诊
        [RequestUtil withPOST:@"/doctor/visit.Visit_close/cancel" parameters:@{@"date":self.currentDate,@"schedule_ids":self.stopids} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if(code == 200){
                [self requestData];
                [TooltipView showMessage:@"接诊成功" offset:0];
            }else{
                [TooltipView showMessage:message offset:0];
            }
        } error:^(NSError *error) {
            [TooltipView showMessage:@"接诊失败，请重试" offset:0];
        }];
    }else{
        //停诊
        [RequestUtil withPOST:@"/doctor/visit.Visit_close/close" parameters:@{@"date":self.currentDate,@"schedule_ids":self.stopids} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if(code == 200){
                [self requestData];
                [TooltipView showMessage:@"停诊成功" offset:0];
            }else{
                [TooltipView showMessage:message offset:0];
            }
        } error:^(NSError *error) {
            [TooltipView showMessage:@"停诊失败，请重试" offset:0];
        }];
    }
}

-(void)tapGestureAction{
    self.stopButton.hidden = YES;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        return self.amArray.count;
    }
    return self.pmArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LGTemporaryStopCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.dataDic = (indexPath.section == 0)?self.amArray[indexPath.row]:self.pmArray[indexPath.row];
    cell.indexPath = indexPath;
    __weak typeof(self) weakSelf = self;
    cell.stopCellAction = ^(BOOL stop, NSString * _Nonnull ids, NSIndexPath * _Nonnull indexPath) {
        weakSelf.stopids = ids;
        [self.tableView bringSubviewToFront:self.stopButton];
        weakSelf.stopButton.hidden = NO;
        weakSelf.stopButton.selected = stop;
        CGFloat pointY = [weakSelf.tableView rectForRowAtIndexPath:indexPath].origin.y;
        weakSelf.stopButton.frame = CGRectMake(Screen_W-viewPix(184), pointY+viewPix(32), viewPix(156), viewPix(83));
    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return viewPix(50);
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    LGCornerHeaderView *headView = [[LGCornerHeaderView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(50))];
    headView.topMargin = viewPix(6);
    NSString *title = (section == 0)?@"上午":@"下午";
    UILabel *titleLabel = [UILabel lableWithText:title colorString:@"#333333" textFont:LGFont(16) textAlignment:NSTextAlignmentLeft lines:1];
    titleLabel.frame = CGRectMake(viewPix(28), viewPix(18), viewPix(50), viewPix(20));
    [headView addSubview:titleLabel];
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(viewPix(28), viewPix(49), Screen_W-viewPix(56), 0.5)];
    lineView.backgroundColor = [UIColor colorWithString:@"#E8E8E8"];
    [headView addSubview:lineView];
    return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if((section == 0 && self.amArray.count == 0) || (section == 1 && self.pmArray.count == 0)){
        return viewPix(55);
    }
    return viewPix(15);
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    CGFloat height = ((section == 0 && self.amArray.count == 0) || (section == 1 && self.pmArray.count == 0))?viewPix(55) : viewPix(15);
    LGCornerFooterView *footView = [[LGCornerFooterView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, height)];
    footView.bottomMargin = viewPix(10);
    if((section == 0 && self.amArray.count == 0) || (section == 1 && self.pmArray.count == 0)){
        UILabel *titleLabel = [UILabel lableWithText:@"暂无排班" colorString:@"#999999" textFont:LGFont(16) textAlignment:NSTextAlignmentLeft lines:1];
        titleLabel.frame = CGRectMake(viewPix(28), viewPix(12), viewPix(100), viewPix(22));
        [footView addSubview:titleLabel];
    }
    return footView;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    self.stopButton.hidden = YES;
}
#pragma mark
#pragma mark ====> 创建控件
-(NSDateFormatter *)formatter{
    if(!_formatter){
        _formatter = [[NSDateFormatter alloc] init];
        _formatter.dateFormat = @"yyyy-MM-dd";
    }
    return _formatter;
}

-(NSDateFormatter *)monthFormatter{
    if(!_monthFormatter){
        _monthFormatter = [[NSDateFormatter alloc] init];
        _monthFormatter.dateFormat = @"yyyy年MM月";
    }
    return _monthFormatter;
}

-(UIButton *)leftButton{
    if(!_leftButton){
        _leftButton = [UIButton buttonWithImage:@"日历-上个月" selectImage:@"日历-上个月"];
        _leftButton.frame = CGRectMake(Screen_W/2.0-viewPix(80), 0, viewPix(30), viewPix(30));
        [_leftButton addTarget:self action:@selector(monthBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _leftButton;
}

-(UIButton *)rightButton{
    if(!_rightButton){
        _rightButton = [UIButton buttonWithImage:@"日历-下个月" selectImage:@"日历-下个月"];
        _rightButton.frame = CGRectMake(Screen_W/2.0+viewPix(50), 0, viewPix(30), viewPix(30));
        [_rightButton addTarget:self action:@selector(monthBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightButton;
}

-(UILabel *)mounthLabel{
    if(!_mounthLabel){
        _mounthLabel = [UILabel lableWithText:[self.monthFormatter stringFromDate:[NSDate date]] colorString:@"#333333" textFont:LGFont(16) textAlignment:NSTextAlignmentCenter lines:1];
        _mounthLabel.frame = CGRectMake(Screen_W/2.0-viewPix(50), 0, viewPix(100), viewPix(30));
    }
    return _mounthLabel;
}

-(FSCalendar *)calendar{
    if(!_calendar){
        _calendar = [[FSCalendar alloc] initWithFrame:CGRectMake(0, viewPix(30), Screen_W, viewPix(255))];
        _calendar.backgroundColor = [UIColor whiteColor];
        _calendar.headerHeight = 0;//设置顶部显示月份的高度
        _calendar.weekdayHeight = viewPix(40);
        _calendar.rowHeight = viewPix(30);
        _calendar.locale = [NSLocale localeWithLocaleIdentifier:@"zh-CN"];
        [_calendar setScope:FSCalendarScopeMonth animated:NO];
        _calendar.appearance.todayColor = [UIColor colorWithString:@"#FFFFFF"];
        _calendar.appearance.titleTodayColor = [UIColor colorWithString:@"#444444"];
        _calendar.appearance.caseOptions = FSCalendarCaseOptionsWeekdayUsesSingleUpperCase;
        _calendar.appearance.weekdayFont = LGFont(16);
        _calendar.appearance.weekdayTextColor = [UIColor colorWithString:@"#666666"];
        _calendar.appearance.titleFont = LGFontWeight(16, UIFontWeightMedium);
        _calendar.appearance.titleDefaultColor = [UIColor colorWithString:@"#444444"];
        _calendar.appearance.titlePlaceholderColor = [UIColor colorWithString:@"#A9A8B6"];
        _calendar.appearance.titleSelectionColor = [UIColor colorWithString:@"#3291FF"];
        _calendar.appearance.selectionColor = [UIColor colorWithString:@"#DFEEFF"];
        _calendar.dataSource = self;
        _calendar.delegate = self;
    }
    return _calendar;
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kMaxY(self.calendar.frame), Screen_W, Screen_H-topBarHeight-viewPix(44)-kMaxY(self.calendar.frame)) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGTemporaryStopCell class] forCellReuseIdentifier:@"cell"];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}

-(UIButton *)stopButton{
    if(!_stopButton){
        _stopButton = [UIButton buttonWithTitle:@"停诊" titleFont:LGFont(16) normalColor:@"#FFFFFF" selectColor:@"#FFFFFF"];
        [_stopButton setTitle:@"接诊" forState:UIControlStateSelected];
        [_stopButton setBackgroundImage:[UIImage imageNamed:@"排班设置-临时停诊"] forState:UIControlStateNormal];
        [_stopButton addTarget:self action:@selector(stopButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        _stopButton.hidden = YES;
    }
    return _stopButton;
}

@end


#define itemHeight  viewPix(22)

@interface LGTemporaryStopCell()
/**   */
@property (nonatomic , strong)UIView *baseView;
/**   */
@property (nonatomic , strong)UILabel *titleLabel;
/**   */
@property (nonatomic , strong)UIButton *statusBtn;
/**   */
@property (nonatomic , strong)NSMutableArray *itemArray;
/**   */
@property (nonatomic , copy)NSString *schedulids;

@end

@implementation LGTemporaryStopCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self createSubView];
    }
    return  self;
}


-(void)setDataDic:(NSDictionary *)dataDic{
    _dataDic = dataDic;
    self.titleLabel.text = LGNSString(dataDic[@"appointment_type_name"]);
    self.statusBtn.selected = ([LGNSString(dataDic[@"is_closed"]) integerValue] == 0)?YES:NO;
    for (UILabel *label in self.itemArray) {
        [label removeFromSuperview];
    }
    [self.itemArray removeAllObjects];
    NSString *ids = @"";
    NSArray *tempArray = dataDic[@"schedules"];
    for (NSInteger i=0; i<tempArray.count; i++) {
        ids = (ids.length == 0)?LGNSString(tempArray[i][@"schedule_id"]):[NSString stringWithFormat:@"%@,%@",ids,tempArray[i][@"schedule_id"]];
        NSString *content = [NSString stringWithFormat:@"%@ - %@",tempArray[i][@"start_time"],tempArray[i][@"end_time"]];
        UILabel *timeLabel = [UILabel lableWithText:content colorString:@"#666666" textFont:LGFont(16) textAlignment:NSTextAlignmentLeft lines:1];
        timeLabel.frame = CGRectMake(viewPix(90), itemHeight*i+viewPix(7), viewPix(130), itemHeight);
        [self.baseView addSubview:timeLabel];
        [self.itemArray addObject:timeLabel];
    }
    self.schedulids = ids;
    [self.baseView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(viewPix(14)+itemHeight*tempArray.count));
    }];
}



//停诊、接诊
-(void)statusBtnAction:(UIButton *)sender{
    if(sender.selected == YES){
        //已停诊
        if(self.stopCellAction){
            self.stopCellAction(NO, self.schedulids, self.indexPath);
        }
    }else{
        //未停诊
        if(self.stopCellAction){
            self.stopCellAction(YES, self.schedulids, self.indexPath);
        }
    }
}


-(void)createSubView{
    self.clipsToBounds = YES;
    self.contentView.backgroundColor = [UIColor colorWithString:@"#F9F9F9"];
    [self.contentView addSubview:self.baseView];
    [self.baseView addSubview:self.titleLabel];
    [self.baseView addSubview:self.statusBtn];
    [self.baseView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.contentView);
        make.left.equalTo(self.contentView).offset(viewPix(16));
        make.right.equalTo(self.contentView).offset(-viewPix(16));
        make.height.equalTo(@(viewPix(14)+itemHeight));
    }];
    [self.statusBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.baseView).offset(-viewPix(12));
        make.centerY.equalTo(self.titleLabel);
        make.width.equalTo(@(viewPix(80)));
        make.height.equalTo(@(viewPix(26)));
    }];
}

-(NSMutableArray *)itemArray{
    if(!_itemArray){
        _itemArray = [NSMutableArray array];
    }
    return _itemArray;
}

-(UIView *)baseView{
    if(!_baseView){
        _baseView = [UIView shadowViewWithColor:@"#B2BDC7" offset:CGSizeMake(0, 2) opacity:0.15 radius:0];
        _baseView.backgroundColor = [UIColor whiteColor];
    }
    return _baseView;
}

-(UILabel *)titleLabel{
    if(!_titleLabel){
        _titleLabel = [UILabel lableWithText:@"" colorString:@"#666666" textFont:LGFont(16) textAlignment:NSTextAlignmentLeft lines:1];
        _titleLabel.frame = CGRectMake(viewPix(12), viewPix(7), viewPix(70), itemHeight);
    }
    return _titleLabel;
}


-(UIButton *)statusBtn{
    if(!_statusBtn){
        _statusBtn = [UIButton buttonWithTitle:@"已停诊" titleFont:LGFont(13) normalColor:@"#333333" selectColor:@"#333333" normalImage:@"门诊咨询-已停诊" selectImage:@"门诊咨询-接诊中"];
        _statusBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _statusBtn.imageEdgeInsets = UIEdgeInsetsMake(0, viewPix(7), 0, 0);
        _statusBtn.titleEdgeInsets = UIEdgeInsetsMake(0, viewPix(10), 0, 0);
        _statusBtn.cornerRidus = viewPix(13);
        [_statusBtn setTitle:@"接诊中" forState:UIControlStateSelected];
        [_statusBtn setBackgroundColor:[UIColor colorWithString:@"#E8E9EB"] forState:UIControlStateNormal];
        [_statusBtn setBackgroundColor:[UIColor colorWithString:@"#DFEEFF"] forState:UIControlStateSelected];
        [_statusBtn addTarget:self action:@selector(statusBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"grayTipDown"]];
        imageView.frame = CGRectMake(viewPix(80)-viewPix(19), viewPix(7), viewPix(12), viewPix(12));
        [_statusBtn addSubview:imageView];
    }
    return _statusBtn;
}


@end
